﻿using BackData;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Server.API.Application.Command;
using Server.API.Application.Command.Goods;
using Server.API.DTOs;
using Infratructure;
using Domain;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;

namespace Server.API.Controllers
{
    /// <summary>
    /// /商品数据控制器+登录
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    // [Authorize]
    public class GoodsController : ControllerBase
    {
        IMediator mediator;
        private readonly IWebHostEnvironment env;
        private readonly IRepository<GoodsModel> goodsway;

        public GoodsController(IMediator mediator, IWebHostEnvironment env, IRepository<GoodsModel> goodsway)
        {
            this.mediator = mediator;
            this.env = env;
            this.goodsway = goodsway;
        }
        /// <summary>
        /// 商品数据导出
        /// </summary>
        /// <param name="number">数据条数</param>
        /// <returns>表格文件</returns>
        [HttpGet]
        public IActionResult Outway([FromQuery]int number)
        {
            byte[]? value = null;  // 返回值
            try
            {
                // 1. 创建工作簿
                IWorkbook workbook = new XSSFWorkbook(); // .xlsx
                                                         // IWorkbook workbook = new HSSFWorkbook(); // .xls

                // 2. 创建工作表
                ISheet sheet = workbook.CreateSheet("员工信息");

                // 3. 创建表头
                IRow headerRow = sheet.CreateRow(0); //  创建行
                headerRow.CreateCell(0).SetCellValue("主键");
                headerRow.CreateCell(1).SetCellValue("产品名称");
                headerRow.CreateCell(2).SetCellValue("生产批次");
                headerRow.CreateCell(3).SetCellValue("保质期");
                headerRow.CreateCell(4).SetCellValue("生产许可证号");
                headerRow.CreateCell(5).SetCellValue("生产企业");
                headerRow.CreateCell(6).SetCellValue("完成状态");
                headerRow.CreateCell(7).SetCellValue("创建人");
                headerRow.CreateCell(8).SetCellValue("创建时间");
                headerRow.CreateCell(9).SetCellValue("修改人");
                var list = goodsway.GetAll().Take(number).ToList(); //获取对应条数的数据
                int i = 0;
                for (i = 0; i < list.Count(); i++)  // 循环写入数据
                {

                    IRow Row = sheet.CreateRow(i + 1); // 创建行
                    Row.CreateCell(0).SetCellValue(list[i].Id.ToString());     
                    Row.CreateCell(1).SetCellValue(list[i].GoodsName.ToString());
                    Row.CreateCell(2).SetCellValue(list[i].Order.ToString());
                    Row.CreateCell(3).SetCellValue(list[i].Expired.ToString());
                    Row.CreateCell(4).SetCellValue(list[i].Allownum.ToString());
                    Row.CreateCell(5).SetCellValue(list[i].Companyname.ToString());
                    Row.CreateCell(6).SetCellValue(list[i].Finiststate.ToString());
                    Row.CreateCell(7).SetCellValue(list[i].Creator.ToString());
                    Row.CreateCell(8).SetCellValue(list[i].Createtime.ToString());
                    Row.CreateCell(9).SetCellValue(list[i].Modifier.ToString());

                }
                // 6. 输出到内存流
                using (var memoryStream = new MemoryStream())
                {
                    workbook.Write(memoryStream);  //写入内存流
                   value= memoryStream.ToArray();   //转为字节数组
                   
                    return File(value, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "商品信息.xlsx");    
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <summary>
        ///登录
        /// </summary>
        /// <param name="request">账号密码</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>用户信息</returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpGet]
        [AllowAnonymous]  //跳过登录
        public Task<APIResult<UserDTO>> Login([FromQuery] LoginCommand request)
        {
            // request.Key = Request.Headers["User-Agent"].FirstOrDefault(); //用户代理 标识客户端: 浏览器 操作系统设备型号 渲染引擎
            try
            {
                return mediator.Send(request);
            }
            catch (Exception)
            {

                throw;
            }

        }

        #region 测试
        /// <summary>
        /// 刷新Token
        /// </summary>
        /// <param name="request">长期Token</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>新的Token</returns>
        /// <exception cref="NotImplementedException"></exception>
        //[HttpGet]
        //[AllowAnonymous]
        //public Task<APIResult<string>> NewToken([FromQuery]NewTokenCommand request)
        //{
        //    return mediator.Send(request);
        //}

        /// <summary>
        /// ToKen测试方法
        /// </summary>
        /// <returns></returns>
        //[HttpPost]
        //public  string TestTokenway()
        //{
        //    return "测试成功";
        //}

        #endregion

        /// <summary>
        ///商品添加    
        /// </summary>
        /// <param name="request">参数</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>影响行数</returns>
        [HttpPost]
        public async Task<APIResult<int>> AddGoods(AddGoodsCommand request)
        {
            try
            {
                return await mediator.Send(request);
            }
            catch (Exception)
            {

                throw;
            }

        }
        /// <summary>
        /// 商品列表
        /// </summary>
        /// <param name="request">参数</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>商品列表</returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpGet]
        public Task<APIPaging<GoodDTO>> GoodsGet([FromQuery] GoodsGetCommand request)
        {
            try
            {
                return mediator.Send(request);
            }
            catch (Exception)
            {

                throw;
            }

        }
        /// <summary>
        /// 删除单个商品
        /// </summary>
        /// <param name="request">主键</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>影响行数</returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpPut]
        public async Task<APIResult<int>> GoodsDel(GoodsDelCommand request)
        {
            try
            {
                return await mediator.Send(request);
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 商品修改
        /// </summary>
        /// <param name="request">参数</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>影响行数</returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpPut]
        public async Task<APIResult<int>> GoodsUpdate(GoodsUpdateCommand request)
        {
            try
            {
                return await mediator.Send(request);
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="file">文件</param>
        /// <returns>文件路径</returns>
        [HttpPost]
        public async Task<IActionResult> Upload(IFormFile file)
        {
            var path = env.WebRootPath + "/Imgs/" + file.FileName;  // 保存路径
            using (FileStream? fs = System.IO.File.Create(path))
            {
                await file.CopyToAsync(fs);
            }
            return Ok("http://localhost:5017/Imgs/" + file.FileName);
        }


        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="request">参数</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>影响行数</returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpPut]
        public async Task<APIResult<int>> GoodsMoreDel(GoodsMoreDelCommand request)
        {
            try
            {
                return await mediator.Send(request);
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 获取单个商品数据
        /// </summary>
        /// <param name="request">商品主键</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>商品信息</returns>
        /// <exception cref="NotImplementedException"></exception>
        [HttpGet]
        public async Task<APIResult<GoodDTO>> OneGetGoods([FromQuery]OneGetGoodsCommand request)
        {
            return await mediator.Send(request);
        }


    }
}
